<template>
	<view class="container" :style="{ paddingTop: statusBarHeight + 'px' }">
		<uni-nav-bar leftIcon="left" left-text="返回" backgroundColor="#4d71f1" color="#ffffff" title="绩效考核"
		 @clickLeft="back" />
		 <view class="container">
		 <uni-forms ref="baseForm" style="margin: 25rpx 25rpx;" :rules="customRules" labelWidth="80px" :modelValue="baseFormData">
			<uni-forms-item label="考核主题" required >
				<uni-easyinput v-model="baseFormData.evaluationTitle" :disabled="readOnly" maxlength="25" placeholder="请输入考核主题" />
			</uni-forms-item>
			<uni-forms-item label="开始日期" required >
				<uni-datetime-picker type="date" :start="minDate"  placeholder="考核开始日期"
									:disabled="readOnly"		v-model="baseFormData.startDate" />
			</uni-forms-item>
			<uni-forms-item label="结束日期" required >								
				<uni-datetime-picker type="date" :start="baseFormData.startDate"  placeholder="考核结束日期"
									:disabled="readOnly"		v-model="baseFormData.endDate" />
			</uni-forms-item>
			<uni-forms-item label="奖励金额" >
				<uni-easyinput v-model="baseFormData.money" type="number" :disabled="readOnly" maxlength="5" placeholder="请输入奖励金额" />
			</uni-forms-item>
			<uni-forms-item label="被考核人" required  size="25" v-model="baseFormData.userIds" class="add-user-class" >			 
				<!-- <uni-easyinput v-model="baseFormData.persons" @focus="showTree" :clearable="!readOnly" :disabled="personselect" placeholder="选择被考核人" /> -->
				<view class="tabs-wrapper">
					<view v-for="(tab, index) in userList" :key="tab.id" class="tab-item">
						<view class="tab-text">
							{{ tab.name }}
						</view>
						<view class="close-btn" @click="closeTab(index,tab.id)">x</view>
					</view>
				</view>
				<uni-icons type="plusempty" color="#5E6D82" size="25" style="background-color: #F0F0F0;" @click="showTree()"></uni-icons>
				<tki-tree ref="tkitree"
						  :range="treeData" 
						  :rangeKey="rangeKey" 
						  :foldAll="true"
						  :multiple="true"
						  :selectParent="false"
						  confirmColor="#4e8af7"
						  @confirm="treeConfirm" 
						  @cancel="treeCancel"/>	
			</uni-forms-item>
			<mp-html v-if="readOnly" :content="baseFormData.content" :lazy-load="true"></mp-html>
			<view class="editor">
				<sp-editor
					editorId="editor"
					:toolbar-config="toolbarConfig"
					v-if="!readOnly"
					@input="inputOver"
					@upinImage="upinImage"
					@init="initEditor"
					@overMax="overMax"
					@exportHtml="exportHtml"
					@addLink="addLink"
					placeholder="考核内容"
				></sp-editor>				
			</view>
		</uni-forms>
		
		<!-- <tki-tree ref="tkitree" :selectParent="selectParent" :multiple="multiple" :range="list" :foldAll="flod"
		 rangeKey="name" @confirm="treeConfirm"
		 @cancel="treeCancel"></tki-tree> -->
		 
		 
		<button type="primary" style="width: 500rpx;" v-if="id==null"  @click="submit('baseForm')">提交</button>
		<button type="warn" style="width: 500rpx;" v-if="id>0 && baseFormData.finish==0"  @click="goEvaluation()">去考核</button>
		</view>
	</view>
</template>

<script>
	import tkiTree from '@/components/tki-tree/tki-tree.vue';
	import { BaseUrl	} from "@/api/report/utils/request";
	import { sendUserTree } from '@/api/report/report';
	import { getUser } from '@/utils/auth';
	export default {
		components: {
			tkiTree
		},
		data() {
			return {
				// 状态栏高度
				statusBarHeight: 100,
				// 基础表单数据
				id: null,
				baseFormData: {
					evaluationTitle : '',
					startDate: new Date().toISOString().slice(0, 10),
					money: null,
					endDate: '',					 
					content: '',
					persons: '',
					personIds: '',
					createDateTime: '',
					finish:0,
					userIds: [],
				},
				treeData: [],
				rangeKey:"name",
				minDate: new Date().toISOString().slice(0, 10),
				multiple: true,
				personselect : false,
				selectParent: false,
				flod: false,
				readOnly: false,			
				userList: [],
				selectPersonId: [],
				// 自定义表单校验规则
				customRules: {
					date: {
						rules: [{
							required: true,
							errorMessage: '日期不能为空'
						}]
					},
					money: {
						rules: [{
							format: 'number',
							errorMessage: '只能输入数字'
						}]
					}						

				},
				editorIns: null,
				toolbarConfig: {
					excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
					iconSize: '15px',
					iconColumns: 10
				},
				content: '',
			}
		},
		async onLoad(options) {		
			this.userList=[];
			this.baseFormData.userIds=[];
			try{
				// 获取传递的参数
				this.id = options.id;		
				// 处理参数，例如输出到控制台
				console.log('获取到的id参数为:', this.id,this.minDate);
				await this.getdeptUser();
				await this.getDetail();
			}catch (error) {
				console.error('请求失败:', error);
			}
			
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.once('e_content', (res) => {
				this.content = res.content
			})
			
		},
		mounted() {
			// 获取设备信息
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight; // 获取状态栏高度
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			//this.$refs.baseForm.setRules(this.customRules)
		},
		methods: {			
			getdeptUser(){
				sendUserTree(getUser().userId).then((res) => {
					this.treeData = res.data;				
				});
				// var url = "/api/Performance/user/tree/"+this.id;
				// if(typeof(this.id)=="undefined"){					
				// 	url = "/api/Performance/user/tree/0";
				// 	console.log('getdeptUser undefined->', url);
				// }
				// this.$myRequest.getRequest(url, null).then(res => {
				// 	console.log('人员列表返回结果->', res);
				// 	this.treeData = res.data;			
				// }).catch(res => { 
				// 	console.log('人员列表返回出错->', res);
				// })
				// const storageData = uni.getStorageSync('userInfo');
				// this.$myRequest.getRequest("/api/dept/getDepartmentsWithUsers", {userId:storageData.userId}).then(res => {
				// 	this.treeData=res;
				// }).catch(res => { 
				// 	uni.showToast({
				// 	  title: '获取部门和用户失败!',
				// 	  icon: 'none'
				// 	});
				// });
			},
			getDetail(){
				var url = "/api/Performance/detail/"+this.id;
				if(typeof(this.id)=="undefined"){
					console.log('return getDetail undefined->', url);
					return;
				}
				this.$myRequest.getRequest(url, null).then(res => {
					console.log('详情返回结果->', res);
					this.baseFormData = res.data;
					this.readOnly = true;
					if (this.baseFormData.finish==1){
						this.personselect = true;
					}					
					setTimeout(() => {
						this.content = this.baseFormData.content;
						this.preRender()
						uni.hideLoading()
					}, 500)
				}).catch(res => { 
					console.log('详情返回出错->', res);
				})
			},
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			saveback(tab) {
				uni.navigateBack({
					delta: 1,
					success() {
					    uni.$emit('update:performance',tab)
					}
				})
			},
			closeTab(index,paramId) {
				// 关闭指定的 tab
				console.log("index",index);
				this.userList.splice(index, 1);
				this.baseFormData.userIds.splice(index, 1);
				const newTreeData = [];
				this.treeData.forEach(item=> {
					const newchildrenArray = [];
					 if(Array.isArray(item.children) && item.children.length > 0){
						 item.children.forEach(citem => {
							 if(paramId === citem.id){
								citem.checked = false
							 }else if(this.userList.some(u => u.id === citem.id)){
								citem.checked = true; 
							 }
							 newchildrenArray.push(citem);
						 }); 
					 }
					 item.children=newchildrenArray;
					 newTreeData.push(item);
				});
				this.treeData=newTreeData;
			},
			// 确定回调事件
			treeConfirm(e) {
				// 必须选择
				console.log(e.length);
				if (e.length == 0) {					 
					this.baseFormData.userIds=[];
					return;
				}
				this.userList=e;
				//this.selectPersonId =[];
				this.baseFormData.userIds=[];
				e.forEach(user => {
					this.baseFormData.userIds.push(user.id);
				    //this.selectPersonId.push(user.id);console.log("checked",user.id);
				});
				console.log("确定回调:",this.baseFormData.userIds);
			},
			// 取消回调事件
			treeCancel(e) {
				console.log(e)
			},
			// 显示树形选择器
			showTree() {
				console.log("showTree")
				this.$refs.tkitree._show();
			},
			submit(ref) {
				console.log(this.content);
				this.baseFormData.content = this.content;
				this.baseFormData.personIds=this.baseFormData.userIds.join(',');
				console.log("提交",this.baseFormData);
				// this.$refs[ref].validate().then(res => {
				// 	console.log('success', res);
				// 	uni.showToast({
				// 		title: `校验通过`
				// 	})
				// }).catch(err => {
				// 	console.log('err', err);
				// })
				this.baseFormData.evaluationTitle = this.baseFormData.evaluationTitle.trim()
				if (this.$kdup.isEmpty(this.baseFormData.evaluationTitle)) {
					uni.showToast({
						title: "考核主题不能为空!",
						icon: "none",
						duration: 1000
					});
					return;
				} 				
				if (this.$kdup.isEmpty(this.baseFormData.startDate.trim())) {
					uni.showToast({
						title: "开始日期不能为空!",
						icon: "none",
						duration: 1000
					});
					return;
				}				
				if (this.$kdup.isEmpty(this.baseFormData.endDate.trim())) {
				 	uni.showToast({
				 		title: "结束日期不能为空!",
				 		icon: "none",
				 		duration: 1000
				 	});
					return;
				}
				if (this.baseFormData.endDate<this.baseFormData.startDate) {
					uni.showToast({
						title: "结束日期不能小于开始日期!",
						icon: "none",
						duration: 1000
					});
					return;
				}
				if (this.$kdup.isEmpty(this.baseFormData.personIds)) {
					uni.showToast({
						title: "选择被考核人不能为空!",
						icon: "none",
						duration: 1000
					});
					return;
				}
				this.content = this.content.replace(/\s+/g, '');
				// if (this.$kdup.isEmpty(this.content)) {
				//  	uni.showToast({
				//  		title: "考核内容不能为空!",
				//  		icon: "none",
				//  		duration: 1000
				//  	});
				// 	return;
				// }
				if (this.countChineseChar(this.baseFormData.content)<5) {
					uni.showToast({
						title: "考核内容字符长度不能少于五个字，不能是空格!",
						icon: "none",
						duration: 1000
					});
					return;
				}
				this.$modal.confirm('确定提交绩效单吗？').then(() => {
					uni.showLoading({title: '提交中',mask:true});
					this.baseFormData.persons='';
					this.$myRequest.postRequest("/api/Performance/createPerformance", this.baseFormData).then(res => {
						setTimeout(function () {uni.hideLoading();}, 100);
						console.log('返回->', res);
						if(res.data.statusCode===0 || res.data.code===-1){
							uni.showToast({
								title: res.data.msg,
								icon: "none",
								duration: 1000
							});
							return;
						}
						let tab = 1;
						if (this.minDate<this.baseFormData.startDate) {
							tab = 0;
						}					
						this.saveback(tab);
						
					});
				})	 
			},
			goEvaluation(){
				console.log('点击了evaluations');
				uni.navigateTo({
					url:'/pages/tab3/evaluations?type=doEvaluation&id='+this.id+"&pid="+this.baseFormData.personIds+'&title='+this.baseFormData.evaluationTitle
				}); 
			},
			countChineseChar(str) {
			    // 使用正则表达式匹配所有的汉字
			    const regex = /[\u4e00-\u9fa5]/g;
			    return (str.match(regex) || []).length;
			},
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
				//console.log('==== inputOver :', e.html)
				this.content = e.html; 
			},
			/**
			 * 超出最大内容限制
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			overMax(e) {
				console.log('==== overMax :', e)
			},
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
				this.editorIns = editor // 保存编辑器实例
				this.$nextTick(() => {
					this.preRender()
				})
			},
			preRender() {
				// 初始化编辑器内容
				this.editorIns.setContents({
					html: this.content
				})
			},
			/**
			 * 直接运行示例工程插入图片无法正常显示的看这里
			 * 因为插件默认采用云端存储图片的方式
			 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
			 * @param {Object} tempFiles
			 * @param {Object} editorCtx
			 */
			upinImage(tempFiles, editorCtx) {
				tempFiles.forEach(async (item) => {
					uni.uploadFile({
						url: BaseUrl + '/api/upload/file',
						filePath: item.path,
						formData: {
							type: 'pic'
						},
						name: 'file',
						success: (result) => {
							uni.hideLoading();
							const param = result.data.split('/');
							editorCtx.insertImage({
								src: BaseUrl + '/api/pic/get?path=' + param[0] + '&filename=' +
									param[1],
								width: '30%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
								success: function() {
									console.log(result);
								}
							});
						}
					});
				});
			},			
			/**
			 * 添加超链接
			 * @param {Object} e { text: '链接描述', href: '链接地址' }
			 */
			addLink(e) {
				console.log('==== addLink :', e)
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		width: 100vw;
		padding-bottom: 100rpx;		
	}
	.editor {
		// height: calc(100% - 100px);
		height: 300px;
		//height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
		width: 100%;
		
	}
	.tabs-wrapper {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 4rpx; 
	}
	 
	.tab-item {
	  font-size: 22rpx;
	  display:flex;
	  flex-direction: row;
	  align-items: center;
	  background-color: #f0f0f0;
	  border-radius: 8rpx;
	  padding: 6rpx 6rpx;
	}
	 
	.tab-text {
	  text-align: left;
	  overflow: hidden;
	  text-overflow: ellipsis;
	  white-space: nowrap;
	}
	 
	.close-btn {
	  background-color: transparent;
	  border: none;
	  font-size: 32rpx;
	  color: #5E6D82;
	  cursor: pointer;
	  margin: 0rpx 0rpx 4rpx 10rpx;
	}
</style>
